import { writeFile } from 'node:fs/promises';

export const routesTpl = (routes, path) => {
  const routeComponents = routes.map((item: any) => {
    return `${item?.id}:React.lazy(() => import('${item?.element}'))`;
  });

  const tpl = `//@ts-nocheck
      import React from 'react';
      export  function getRoutes() {
      const routes = ${JSON.stringify(routes)} as const;
      return {
        routes,
        routeComponents:{${routeComponents ? `${routeComponents}` : ''}},
      };
      }
    `;
  writeFile(path, tpl);
};

export const runtimeTpl = (path) => {
  const tpl = `
 import {
  createBrowserRouter,
  RouterProvider as BrowserRouterProvider,
} from "react-router-dom";
import { getRoutes } from "./routes";
import { Suspense } from "react";
function buildTree(departments, routeComponents) {
  const map = new Map();
  let root;

  departments.forEach((item) => {
    const View = routeComponents?.[item?.id];
    map.set(item.id, {
      ...item,
      element: (
        <Suspense fallback={<div>Loading...</div>}>
          <View />
        </Suspense>
      ),
      children: [],
    });
    if (item.pid === "0") {
      root = map.get(item.id);
    } else {
      const parent = map.get(item.pid);
      if (parent) {
        parent.children.push(map.get(item.id));
      }
    }
  });

  return [root];
}

export const RouterProvider = () => {
  const { routes, routeComponents } = getRoutes();
  const router = createBrowserRouter(buildTree(routes, routeComponents));
  return <BrowserRouterProvider router={router} />;
};
 `;
  writeFile(path, tpl);
};
